<template>
  <a-drawer :open="open" :width="800" title="收费" destroy-on-close root-class-name="z-[1001]" @close="onCancel">
    <a-form :model="formState" class="form-style-flex" :label-col="{ style: { width: '100px' } }">
      <a-form-item label="会员余额" class="w-1/2">
        <div class="text-red-500 font-bold flex items-center text-lg">
          ￥
          <div class="pl-1 text-lg">{{ formatAmount(businessData.rechargeamount) }}</div>
        </div>
      </a-form-item>
      <a-form-item label="赠送金额" class="w-1/2">
        <div class="text-red-500 font-bold flex items-center text-lg">
          ￥
          <div class="pl-1 text-lg">{{ formatAmount(businessData.giveamount) }}</div>
        </div>
      </a-form-item>
      <a-form-item label="充值金额" class="w-1/2" :rules="[{ required: true, message: '请输入充值金额' }]">
        <a-input v-model:value="formState.balance" v-input:float size="large" placeholder="请输入" @blur="onBlurReceipts">
          <template #suffix> <span class="text-gray-400">元</span> </template>
        </a-input>
      </a-form-item>
      <a-form-item label="赠送金额" class="w-1/2">
        <a-input v-model:value="formState.givebalance" v-input:float size="large" placeholder="请输入">
          <template #suffix> <span class="text-gray-400">元</span> </template>
        </a-input>
      </a-form-item>
      <a-form-item label="备注" class="w-full">
        <a-textarea v-model:value="formState.memo" :rows="5" size="large" placeholder="请输入" />
      </a-form-item>
    </a-form>
    <a-form :model="formState" class="cost-form-style pb-4 flex flex-col" :label-col="{ style: { width: '100px' } }">
      <div class="flex justify-end items-center text-lg font-bold">
        实收金额：<span class="text-red-500 text-xl">￥{{ formatAmount(formState.ssje) }}</span>
      </div>
      <a-divider />
      <div class="flex-1 flex flex-col">
        <a-radio-group v-if="systemConfig.isOpenPayCode" v-model:value="payType" button-style="solid" size="large" class="w-full flex px-8">
          <a-radio-button value="1">普通支付</a-radio-button>
          <a-radio-button value="2">扫码支付</a-radio-button>
        </a-radio-group>
        <div v-if="payType === '1'" class="flex flex-wrap mt-6 flex-1 content-start overflow-auto">
          <template v-for="item in chargeWayList" :key="item.id">
            <a-form-item v-if="!item.disabled" :label="item.zffsmc" class="w-1/2">
              <a-input-group class="!flex">
                <a-input
                  :key="item.zffsdm"
                  v-model:value="formState[item.zffsdm]"
                  v-input-selection
                  size="large"
                  placeholder="0.00"
                  :disabled="item.disabled || formState.ssje === 0"
                  @blur="onBlur(item.zffsdm)"
                  @change="handlerChangePrice(item.zffsdm)"
                >
                  <template #prefix> <span class="text-gray-400">￥</span> </template>
                </a-input>
                <a-button class="!w-10 !rounded-l-none" :disabled="item.disabled || formState.ssje === 0" size="large" @click="onClickAllAmount(item)">
                  <template #icon><ArrowLeftOutlined class="text-gray-400 text-xs" /></template>
                </a-button>
              </a-input-group>
            </a-form-item>
          </template>
        </div>
        <div v-else class="h-60 mt-6 px-8">
          <a-input ref="payCodeInputRef" v-model:value="payCode" size="large" placeholder="扫码支付" @keyup.enter="onOk" />
        </div>
      </div>
      <a-divider style="margin-top: 380px" />
      <div class="flex justify-end items-center">
        <div class="mr-4">
          找零
          <span class="text-red-500 font-bold">
            ￥ <span class="pl-1">{{ formatAmount(formState.changeAmount) }}</span>
          </span>
        </div>
        <div>
          <a-button type="default" class="mr-2" @click="onCancel">取消</a-button>

          <a-button type="primary" :disabled="(disabledState && !payCode && formState.ssje !== 0) || !formState.balance" :loading="loading" @click="onOk"
            >确定</a-button
          >
        </div>
      </div>
    </a-form>
  </a-drawer>
</template>
<script setup>
import { onMounted, ref, watch } from 'vue'
import { ArrowLeftOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import { formatAmount } from '@/utils/format.js'
import { getSystemConfig } from '@/utils/systemConfig'

const emit = defineEmits(['update:open', 'success'])
const props = defineProps({
  open: Boolean,
  brId: {
    type: String,
    desc: '病人Id 用于获取优惠券',
    default: ''
  },
  businessData: {
    type: Object,
    desc: '业务数据',
    default: () => ({})
  },
  isYsje: {
    desc: '是否显示应收金额',
    type: Boolean,
    default: true
  }
})

const chargeWayList = ref([])
const loading = ref(false)
const formState = ref({
  ysje: 0, // 应收金额
  ssje: 0, // 实收金额
  changeAmount: 0 // 找零
})
// const realAmount = ref(0) // 实收金额
const payType = ref('1')
const payCode = ref()
const ePayTotal = ref(0) // 电子支付的总和
const priceAll = ref(0) // 全部的总和
const disabledState = ref(true)
const systemConfig = ref({})

// 充值金额失焦点获取比例
const onBlurReceipts = async () => {
  if (formState.value.balance) {
    formState.value.ssje = formState.value.balance
    const { code, data, msg } = await post('/common/emp/getMembershipRechargeRatio')
    if (code !== 0) return message.error(msg)
    data && (formState.value.givebalance = (Number(formState.value.balance) * Number(data?.s_value)) / 100)
  }
}

// 找零=现金+电子支付-实收金额
const onCalcChange = () => {
  const change = +formState.value['xjzf'] + ePayTotal.value - Number(formState.value.ssje)
  formState.value.changeAmount = formatAmount(change < 0 ? 0 : change)
}

// 收费方式输入
const handlerChangePrice = (zffsdm = '') => {
  ePayTotal.value = 0
  priceAll.value = 0
  // 限制输入内容的范围
  formState.value[zffsdm] = formState.value[zffsdm].replace(/[^\d.]/g, '')
  // 计算电子支付的总和
  chargeWayList.value.forEach((list) => {
    if (list.zffsdm !== 'xjzf' && !list.disabled) {
      ePayTotal.value += Number(formState.value[list.zffsdm] || 0)
    }
  })
  ePayTotal.value = +formatAmount(ePayTotal.value)
  // 判断电子支付的总和是否大于实收金额
  if (ePayTotal.value > formState.value.ssje) {
    formState.value['xjzf'] = null
    formState.value.changeAmount = 0
    setTimeout(() => (formState.value[zffsdm] = ''), 100)
    return message.error('电子支付累计金额不可大于实收金额')
  }
  // 判断当前输入的是否是现金金额
  if (zffsdm === 'xjzf') {
    // 如果现金+电子支付>实收金额，计算找零
    if (+formState.value['xjzf'] + ePayTotal.value > +formState.value.ssje) {
      onCalcChange()
    } else {
      formState.value.changeAmount = 0
    }
  } else {
    // 判断电子支付金额是否等于0，如果不等于，判断实收金额是否大于电子支付金额或者是否相等
    if (ePayTotal.value !== 0) {
      if (formState.value.ssje > ePayTotal.value || formState.value.ssje === ePayTotal.value) {
        // 现金=实收金额-电子支付
        const cash = formState.value.ssje - ePayTotal.value < 0 ? 0 : formatAmount(formState.value.ssje - ePayTotal.value)
        formState.value['xjzf'] = +cash ? formatAmount(cash) : '0.00'
        onCalcChange()
      }
    } else {
      formState.value['xjzf'] = '0.00'
    }
  }

  for (const key in formState.value) {
    priceAll.value += Number(formState.value[key])
  }
  if (
    Number(formatAmount(priceAll.value)) > Number(formatAmount(formState.value.ssje)) ||
    Number(formatAmount(priceAll.value)) === Number(formatAmount(formState.value.ssje))
  ) {
    disabledState.value = false
  } else {
    disabledState.value = true
  }
}

// 判断优惠金额和支付，鼠标离开保留两位
const onBlur = (zffsdm = '') => {
  if (zffsdm !== '') {
    formState.value[zffsdm] = formState.value[zffsdm] ? formatAmount(formState.value[zffsdm]) : ''
  }
}
// 单项全部收费
const onClickAllAmount = (item) => {
  formState.value['xjzf'] = ''
  formState.value[item.zffsdm] = ''
  let doneAmount = 0
  chargeWayList.value.forEach((list) => {
    if (list.zffsdm !== 'xjzf' && !list.disabled) {
      doneAmount += Number(formState.value[list.zffsdm] || 0)
    }
  })
  doneAmount = formatAmount(doneAmount)
  // chargeWayList.value.forEach((list) => !list.disabled && (formState.value[list.zffsdm] = ''))
  const lastAmount = Math.abs(formState.value.ssje) - doneAmount
  formState.value[item.zffsdm] = lastAmount > 0 ? formatAmount(lastAmount) : ''
  lastAmount > 0 && (formState.value.changeAmount = 0)
  disabledState.value = false
}
const onRest = () => {
  formState.value = {}
  formState.value.changeAmount = 0
}
// const disposePrice = ref(0)

// 获取收费当时列表
const getChargeTypeList = async () => {
  const { code, data } = await post('/outp/oupCharge/getChargeTypeList')
  if (code !== 0) return
  chargeWayList.value = data.map((item) => {
    item.disabled = ['dyqzf', 'vipzf', 'yjzf'].includes(item.zffsdm)
    return item
  })
}

// 确定
const onOk = async () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 3000)
  const discountAmount = Number(formState.value.zjyh || 0) + Number(formState.value.vipzf || 0) + Number(formState.value.couponAmount || 0)
  if (discountAmount > formState.value.ysje) {
    return message.error('优惠金额不能大于应收金额')
  }
  const chargeData = { ...formState.value }
  chargeWayList.value.forEach((item) => {
    chargeData[item.zffsdm] = chargeData[item.zffsdm] ? +chargeData[item.zffsdm] : 0
  })
  const params = {
    ...chargeData,
    barCode: payCode.value,
    zffs: payType.value,
    change: formState.value.changeAmount,
    balance: formState.value.balance,
    givebalance: formState.value.givebalance,
    memo: formState.value.memo,
    cardId: props.businessData.cardId,
    ysje: formState.value.ssje,
    ssje: formState.value.ssje,
    brId: props.brId,
    cardNo: props.businessData.cardNo
  }
  const { code, data, msg } = await post('/outp/oupCharge/doSaveOutPFeeVIP', params)
  if (code !== 0) return message.error(msg)
  onPrint(data)
  message.success(msg)
  emit('update:open', false)
  emit('success')
}

const onPrint = async (row) => {
  const { code, msg, data } = await post('/outp/outPrint/getPrintMemberRecharge', { pjhm: row.pjhm, hykh: props.businessData.cardNo })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}

//计算实收&分币
// const getRealityMoney = async (isDispose) => {
//   formState.value['yjzf'] = formatAmount(disposePrice.value)
//   const discountAmount = Number(formState.value.zjyh || 0) + Number(formState.value.vipzf || 0) + Number(formState.value.couponAmount || 0)
//   if (discountAmount > formState.value.ysje - (formState.value.fbwc || 0) - disposePrice.value) {
//     return message.error('优惠金额不能大于应收金额')
//   }
//   const { code, data, msg } = await post('/outp/oupCharge/getPennyDiscount', {
//     ysje: props.businessData.outPocketAmountResponse?.ssje ?? props.businessData.ysje, //应收金额
//     yhje: formState.value.zjyh || 0,
//     vipzf: formState.value.vipzf || 0,
//     // lsh: formState.value.deposit, // 押金单号
//     chargeDepositlsh: chargeDepositlsh.value,
//     patientCouponsId: formState.value.patientCouponsId, // 优惠券id
//     offsetAmount: formState.value.couponAmount // 优惠券金额
//   })
//   if (code !== 0) {
//     disabledState.value = true
//     isDispose && (chargeDepositlsh.value = [])
//     return message.error(msg || '获取实收金额失败')
//   }
//   formState.value.ssje = data.ssje || 0
//   formState.value.fbwc = data.fbwc || 0
//   formState.value.fbyh = data.fbwc || 0
// }

watch(
  () => props.open,
  (val) => {
    if (val) {
      getChargeTypeList()
      // getRealityMoney()
      disabledState.value = true
      payCode.value = ''
      payType.value = '1'
    }
    onRest()
  },
  { immediate: true }
)
const payCodeInputRef = ref()

watch(
  payType,
  (val) => {
    payCode.value = ''
    setTimeout(() => val === '2' && payCodeInputRef.value?.focus(), 100)
  },
  { immediate: true }
)

const onCancel = () => {
  emit('update:open', false)
}
onMounted(() => {
  systemConfig.value = {
    isOpenPayCode: getSystemConfig('IS_CHARGE_SCAN_PAY') === '1', //扫码支付
    isCoupon: getSystemConfig('ENABLE_REGISTER_DISCOUNT') === '1', //收费标准
    isChs: getSystemConfig('IS_EXIST_MEDICAL_INSURANCE') === '1', //是否启用医保
    isChargeStandard: getSystemConfig('ENABLE_CHARGE_STANDARD_MODE') === '1' //启用挂号优惠功能
  }
})
</script>
<style lang="less" scoped>
:deep(.ant-radio-button-wrapper) {
  flex: 1;
  color: var(--primary-color);
  text-align: center;
  border-color: var(--primary-color);
  &::before {
    background-color: var(--primary-color);
  }
}

.cost-form-style {
  :deep(.ant-form-item) {
    padding: 0 3px;

    .ant-form-item-label {
      width: 75px;
      padding-top: 4px;
      label {
        color: #5d5d5d;
        font-size: 16px;
      }
    }
    .ant-form-item-control {
      flex: none;
      width: 240px;
      color: #2b2b2b;
      font-size: 15px;
      .ant-input {
        text-align: right;
      }
      .ant-btn {
        border-left-color: transparent;
      }
    }
  }
  .ant-divider {
    margin: 12px 0;
  }
}
.in-title {
  color: #a4adb3;
}
:deep(.ant-checkbox + span) {
  width: 100%;
}
</style>
